/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * DetalheMesPanel.java
 *
 * Created on Jun 22, 2011, 11:39:50 AM
 */
package br.com.tbp.gui.financeiro;

import br.com.tbp.controle.ControleConta;
import br.com.tbp.exception.PersistenciaException;
import br.com.tbp.gui.BaixaContaDialog;
import br.com.tbp.gui.MenuPrincipal;
import br.com.tbp.model.domain.financeiro.Conta;
import br.com.tbp.utils.DateUtils;
import com.towel.swing.table.TableFilter;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.text.MaskFormatter;

/**
 *
 * @author Diego
 */
public class MesPanel extends javax.swing.JPanel {

    private MenuPrincipal menu;
    private ContasDialog pai;
    private ContasTableModel model;
    private TableFilter filter;
    private MaskFormatter mask = null;
    private int mes;
    private int ano;

    public MesPanel(MenuPrincipal m, ContasDialog c, int mes, int ano) {
        initComponents();
        this.menu = m;
        this.pai = c;
        this.mes = mes;
        this.ano = ano;
        pesquisarContas();
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        group1 = new javax.swing.ButtonGroup();
        popup = new javax.swing.JPopupMenu();
        option1 = new javax.swing.JMenuItem();
        option2 = new javax.swing.JMenuItem();
        option3 = new javax.swing.JMenuItem();
        contentPanel = new javax.swing.JPanel();
        split1 = new javax.swing.JSplitPane();
        jPanel6 = new javax.swing.JPanel();
        scrollpane = new javax.swing.JScrollPane();
        tabela = new javax.swing.JTable();
        jPanel3 = new javax.swing.JPanel();
        jPanel4 = new javax.swing.JPanel();
        adicionarButton = new javax.swing.JButton();
        editarButton = new javax.swing.JButton();
        excluiButton = new javax.swing.JButton();
        jPanel5 = new javax.swing.JPanel();
        msgLabel = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        baixarLink = new org.jdesktop.swingx.JXHyperlink();
        imprimirLink = new org.jdesktop.swingx.JXHyperlink();
        buscaPanel = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        radio1 = new javax.swing.JRadioButton();
        radio2 = new javax.swing.JRadioButton();
        radio3 = new javax.swing.JRadioButton();
        jLabel2 = new javax.swing.JLabel();
        inputTextField = new javax.swing.JFormattedTextField();
        okButton = new javax.swing.JButton();

        option1.setText("Option 1");
        popup.add(option1);

        option2.setText("Option 2");
        popup.add(option2);

        option3.setText("Option 3");
        popup.add(option3);

        setLayout(new java.awt.BorderLayout());

        contentPanel.setLayout(new java.awt.BorderLayout());

        jPanel6.setLayout(new java.awt.BorderLayout());

        scrollpane.setPreferredSize(new java.awt.Dimension(600, 350));

        tabela.setFont(new java.awt.Font("Arial", 0, 14));
        tabela.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        tabela.setRowHeight(20);
        tabela.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tabelaMouseClicked(evt);
            }
        });
        scrollpane.setViewportView(tabela);

        jPanel6.add(scrollpane, java.awt.BorderLayout.CENTER);

        jPanel3.setLayout(new java.awt.BorderLayout());

        adicionarButton.setText("Adicionar");
        adicionarButton.setPreferredSize(new java.awt.Dimension(90, 25));
        adicionarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                adicionarButtonActionPerformed(evt);
            }
        });
        jPanel4.add(adicionarButton);

        editarButton.setText("Editar");
        editarButton.setPreferredSize(new java.awt.Dimension(90, 25));
        editarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editarButtonActionPerformed(evt);
            }
        });
        jPanel4.add(editarButton);

        excluiButton.setText("Excluir");
        excluiButton.setPreferredSize(new java.awt.Dimension(90, 25));
        excluiButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                excluiButtonActionPerformed(evt);
            }
        });
        jPanel4.add(excluiButton);

        jPanel3.add(jPanel4, java.awt.BorderLayout.LINE_END);

        jPanel5.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 4, 1, 1));
        jPanel5.setLayout(new java.awt.BorderLayout());

        msgLabel.setForeground(new java.awt.Color(255, 0, 153));
        msgLabel.setText("mensagem");
        msgLabel.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jPanel5.add(msgLabel, java.awt.BorderLayout.PAGE_END);

        jPanel3.add(jPanel5, java.awt.BorderLayout.LINE_START);

        jPanel6.add(jPanel3, java.awt.BorderLayout.PAGE_START);

        jPanel1.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        baixarLink.setForeground(new java.awt.Color(0, 153, 0));
        baixarLink.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/lapis_16.png"))); // NOI18N
        baixarLink.setText("dar baixa");
        baixarLink.setToolTipText("Selecione uma conta para dar baixa");
        baixarLink.setEnabled(false);
        baixarLink.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                baixarLinkActionPerformed(evt);
            }
        });
        jPanel1.add(baixarLink);

        imprimirLink.setForeground(new java.awt.Color(255, 51, 0));
        imprimirLink.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/print_16.png"))); // NOI18N
        imprimirLink.setText("imprimir");
        imprimirLink.setToolTipText("Selecione uma conta para dar baixa");
        imprimirLink.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                imprimirLinkMousePressed(evt);
            }
        });
        jPanel1.add(imprimirLink);

        jPanel6.add(jPanel1, java.awt.BorderLayout.PAGE_END);

        split1.setRightComponent(jPanel6);

        buscaPanel.setBackground(java.awt.SystemColor.scrollbar);
        buscaPanel.setPreferredSize(new java.awt.Dimension(250, 406));

        jLabel1.setText("Busca simples");

        radio1.setBackground(java.awt.SystemColor.scrollbar);
        group1.add(radio1);
        radio1.setSelected(true);
        radio1.setText("Descrição da conta");
        radio1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                radio1ActionPerformed(evt);
            }
        });

        radio2.setBackground(java.awt.SystemColor.scrollbar);
        group1.add(radio2);
        radio2.setText("Data");
        radio2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                radio2ActionPerformed(evt);
            }
        });

        radio3.setBackground(java.awt.SystemColor.scrollbar);
        group1.add(radio3);
        radio3.setText("Valor R$");
        radio3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                radio3ActionPerformed(evt);
            }
        });

        jLabel2.setText("Selecione o filtro abaixo e digite para buscar:");

        inputTextField.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 5, 1, 1));
        inputTextField.setToolTipText("Selecione o filtro abaixo e digite para buscar");
        inputTextField.setFocusLostBehavior(javax.swing.JFormattedTextField.PERSIST);
        inputTextField.setFont(new java.awt.Font("Dialog", 0, 15));
        inputTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                inputTextFieldActionPerformed(evt);
            }
        });

        okButton.setText("OK");
        okButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout buscaPanelLayout = new javax.swing.GroupLayout(buscaPanel);
        buscaPanel.setLayout(buscaPanelLayout);
        buscaPanelLayout.setHorizontalGroup(
            buscaPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(buscaPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(buscaPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jLabel1)
                    .addGroup(buscaPanelLayout.createSequentialGroup()
                        .addComponent(inputTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 199, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(okButton))
                    .addComponent(radio3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(radio2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(radio1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        buscaPanelLayout.setVerticalGroup(
            buscaPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(buscaPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(buscaPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(inputTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(radio1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(radio2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(radio3)
                .addContainerGap(236, Short.MAX_VALUE))
        );

        split1.setLeftComponent(buscaPanel);

        contentPanel.add(split1, java.awt.BorderLayout.CENTER);

        add(contentPanel, java.awt.BorderLayout.CENTER);
    }// </editor-fold>//GEN-END:initComponents

    private void tabelaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tabelaMouseClicked
        Conta c = model.getConta(tabela.getSelectedRow());
        baixarLink.setEnabled(!c.isQuitada());
        if (evt.getClickCount() == 2) {
            this.editar(tabela.getSelectedRow());
        }
}//GEN-LAST:event_tabelaMouseClicked

    private void editarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editarButtonActionPerformed
        this.editar(tabela.getSelectedRow());
}//GEN-LAST:event_editarButtonActionPerformed

    private void adicionarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cadastrarButtonActionPerformed
        ContaDialog dialog = new ContaDialog(this.menu, "TBP - Conta", true);
        dialog.setConta(new Conta());
        dialog.setNovaConta(true);
        dialog.setVisible(true);
        if (dialog.refresh()) {
            pesquisarContas();
        }
}//GEN-LAST:event_cadastrarButtonActionPerformed

    private void radio1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radio1ActionPerformed
        instalaMask(false);
        inputTextField.requestFocus();
        inputTextField.selectAll();
}//GEN-LAST:event_radio1ActionPerformed

    private void radio2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radio2ActionPerformed
        instalaMask(true);
        inputTextField.requestFocus();
        inputTextField.selectAll();
}//GEN-LAST:event_radio2ActionPerformed

    private void radio3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radio3ActionPerformed
        instalaMask(false);
        inputTextField.requestFocus();
        inputTextField.selectAll();
}//GEN-LAST:event_radio3ActionPerformed

    private void inputTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_inputTextFieldActionPerformed
        buscaConta(inputTextField.getText());
}//GEN-LAST:event_inputTextFieldActionPerformed

    private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
        buscaConta(inputTextField.getText());
}//GEN-LAST:event_okButtonActionPerformed

    private void excluiButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_excluiButtonActionPerformed
        this.excluir(tabela.getSelectedRow());
    }//GEN-LAST:event_excluiButtonActionPerformed

    private void baixarLinkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_baixarLinkActionPerformed
        int row = tabela.getSelectedRow();
        if (row >= 0) {
            Conta c = model.getConta(row);
            if (c != null) {
                BaixaContaDialog dialog = new BaixaContaDialog(this.menu, true, c);
                dialog.setVisible(true);
                boolean baixou = dialog.isBaixou();
                if (baixou) {
                    model.fireTableDataChanged();
                    baixarLink.setEnabled(!baixou);
                }
            }
        }
    }//GEN-LAST:event_baixarLinkActionPerformed

    private void imprimirLinkMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_imprimirLinkMousePressed
        popup.show(evt.getComponent(), evt.getX(), evt.getY());
    }//GEN-LAST:event_imprimirLinkMousePressed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton adicionarButton;
    private org.jdesktop.swingx.JXHyperlink baixarLink;
    private javax.swing.JPanel buscaPanel;
    private javax.swing.JPanel contentPanel;
    private javax.swing.JButton editarButton;
    private javax.swing.JButton excluiButton;
    private javax.swing.ButtonGroup group1;
    private org.jdesktop.swingx.JXHyperlink imprimirLink;
    private javax.swing.JFormattedTextField inputTextField;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JLabel msgLabel;
    private javax.swing.JButton okButton;
    private javax.swing.JMenuItem option1;
    private javax.swing.JMenuItem option2;
    private javax.swing.JMenuItem option3;
    private javax.swing.JPopupMenu popup;
    private javax.swing.JRadioButton radio1;
    private javax.swing.JRadioButton radio2;
    private javax.swing.JRadioButton radio3;
    private javax.swing.JScrollPane scrollpane;
    private javax.swing.JSplitPane split1;
    private javax.swing.JTable tabela;
    // End of variables declaration//GEN-END:variables

    private void buscaConta(String texto) {
        try {
            ControleConta controle = new ControleConta();
            List<Conta> lista = null;
            if (radio1.isSelected()) {
                lista = controle.pesquisarPor(texto, this.mes, this.ano);
            } else if (radio2.isSelected()) {
                lista = controle.pesquisarPor(DateUtils.dataStringParaObjeto(texto));
            } else if (radio3.isSelected()) {
                try {
                    lista = controle.pesquisarPor(Double.parseDouble(texto), this.mes, this.ano);
                } catch (NumberFormatException nfex) {
                    lista = new ArrayList<Conta>();
                }
            }
            this.updateTable(lista);
            inputTextField.selectAll();
        } catch (PersistenciaException pex) {
            System.out.println(pex.getMessage());
        }
    }

    public void foco() {
        inputTextField.requestFocus();
    }

    private void updateTable(List<Conta> lista) {
        model = new ContasTableModel(lista);
        //Criar stubs de contas
        //model = new ContasTableModel(ContasTableModel.createContasList());

        tabela.setModel(model);
        /* Comportamentos adicionais: filtrar e ajustar o o tamanho das colunas */
        filter = new TableFilter(tabela);
        //JTableUtils.fitAllColumns(tabela);

        if (model.getRowCount() > 0) {
            tabela.getColumnModel().getColumn(0).setPreferredWidth(32);
            tabela.getColumnModel().getColumn(1).setPreferredWidth(30);
            tabela.getColumnModel().getColumn(2).setPreferredWidth(350);
            tabela.getColumnModel().getColumn(3).setPreferredWidth(50);
        }
        int linhas = model.getRowCount();
        String contas = linhas != 1 ? linhas + " contas registradas" : linhas + " conta registrada";
        msgLabel.setText("Exibindo " + contas);
    }

    private void pesquisarContas() {
        try {
            ControleConta controle = new ControleConta();
            List<Conta> lista = controle.pesquisar(this.mes, this.ano);
            this.updateTable(lista);
        } catch (PersistenciaException pex) {
            System.out.println(pex.getMessage());
        }
    }

    private void editar(int linha) {
        if (linha >= 0) {
            Conta c = model.getConta(filter.getModelRow(linha));
            if (c != null) {
                ContaDialog dialog = new ContaDialog(menu, "TBP - Conta", true);
                dialog.setConta(c);
                dialog.setNovaConta(false);
                dialog.setVisible(true);
                if (dialog.refresh()) {
                    model.fireTableDataChanged();
                    tabela.setRowSelectionInterval(linha, linha);
                }
            }
        }
    }

    private void excluir(int linha) {
        if (linha >= 0) {
            Conta c = model.getConta(linha);
            if (c != null) {
                Object[] opcoes = {"Sim", "Não"};
                int resposta = JOptionPane.showOptionDialog(this,
                        "Confirma excluir a conta nº " + c.getId() + " ?",
                        "Atenção", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
                        null, opcoes, opcoes[1]);
                if (resposta == 0) {
                    try {
                        ControleConta controle = new ControleConta();
                        if (controle.excluir(c) == true) {
                            model.excluiConta(linha);
                        }
                    } catch (PersistenciaException pex) {
                        System.out.println(pex.getMessage());
                    }
                }
            }
        }
    }

    private void instalaMask(boolean install) {
        if (mask == null) {
            try {
                String dataMask = null;
                if (this.mes < 10) {
                    dataMask = "##/0" + this.mes + "/" + this.ano;
                } else {
                    dataMask = "##/" + this.mes + "/" + this.ano;
                }
                mask = new MaskFormatter(dataMask);
            } catch (ParseException pex) {
            }
        }
        if (install) {
            mask.install(inputTextField);
        } else {
            mask.uninstall();
        }
    }
}
